var duration = 0; //停留时间
var loadingTime = 0; //加载时间
var startTime = Math.ceil(new Date().getTime() / 10);

//异步请求
function postData(url, data) {
    var formData = [];
    for (var key in data) {
        formData.push(''.concat(key, '=', data[key]));
    }
    // return fetch('http://localhost/whatsapp/public/index.php' + url, {
    return fetch('http://localhost:8888/whatsapp/public/index.php' + url, {
        body: formData.join('&'),
        headers: {
            'Accept': 'application/json',
            'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST'
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            return { "code": -1 };
        }
    })
}

//判断是否为空
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
}

//设置本地存储
function setLocalData(key, value, time) {
    const date = new Date().getTime();
    localStorage.setItem(key, JSON.stringify({ value, date, time }));
}

//设置本地存储
function getLocalData(key) {
    const item = localStorage.getItem(key) || '';
    if (item) {
        const date = new Date().getTime();
        const { value, date: oldDate, time } = JSON.parse(item);
        console.log(date - oldDate, time);
        if (date - oldDate >= time) {
            localStorage.removeItem(key);
            return null;
        } else {
            return value;
        }
    }
    console.log(item);
    return null;
}

//记录点击
function uploadClick(clickType, clickLocation) {
    if (!isEmpty(record_id)) {
        param = {
            "record_id": record_id,
            'click_type': clickType,
            'location': clickLocation,
            'duration': duration
        }

        postData("/api/track/userclick", param).then(rsp => {
            console.log(rsp.code);
        });
    }
}

//停留时时间
setInterval(function () {
    duration++;
}, 1000);